<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 客户基础数据模型
 */
class Customer extends Model
{
    // 表名
    protected $name = 'scanwork_customer';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'status_text'
    ];
    
    // 客户状态
    public function getStatusList()
    {
        return [
            '0' => __('禁用'),
            '1' => __('正常')
        ];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 关联订单
    public function orders()
    {
        return $this->hasMany('app\admin\model\scanwork\Order', 'customer_name', 'customer_name');
    }

    // 关联产品溯源
    public function traceabilities()
    {
        return $this->hasMany('app\admin\model\scanwork\Traceability', 'customer_id', 'id');
    }

    // 获取客户编码
    public function getCustomerCodeAttr($value, $data)
    {
        if (empty($value) && isset($data['id'])) {
            $value = 'KH-' . date('Y') . '-' . str_pad($data['id'], 3, '0', STR_PAD_LEFT);
        }
        return $value;
    }

    // 检查客户编码是否唯一
    public function checkCodeUnique($code, $id = null)
    {
        $where = ['customer_code' => $code];
        if ($id) {
            $where['id'] = ['<>', $id];
        }
        return $this->where($where)->count() == 0;
    }

    // 获取客户订单历史
    public function getOrderHistoryAttr($value, $data)
    {
        if (empty($value) && isset($data['id'])) {
            $orders = $this->orders()->field('order_no,createtime,total_quantity,status')->order('createtime desc')->limit(10)->select();
            $history = [];
            foreach ($orders as $order) {
                $history[] = [
                    'order_no' => $order->order_no,
                    'date' => date('Y-m-d', $order->createtime),
                    'quantity' => $order->total_quantity,
                    'status' => $order->status_text
                ];
            }
            return json_encode($history, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 自动更新订单历史
    public function updateOrderHistory()
    {
        $orders = $this->orders()->field('order_no,createtime,total_quantity,status')->order('createtime desc')->limit(10)->select();
        $history = [];
        foreach ($orders as $order) {
            $history[] = [
                'order_no' => $order->order_no,
                'date' => date('Y-m-d', $order->createtime),
                'quantity' => $order->total_quantity,
                'status' => $order->status_text
            ];
        }
        $this->save(['order_history' => json_encode($history, JSON_UNESCAPED_UNICODE)]);
    }

    // 获取客户统计信息
    public function getCustomerStats()
    {
        $orderCount = $this->orders()->count();
        $totalQuantity = $this->orders()->sum('total_quantity');
        $completedOrders = $this->orders()->where('status', 2)->count();
        
        return [
            'order_count' => $orderCount,
            'total_quantity' => $totalQuantity,
            'completed_orders' => $completedOrders,
            'completion_rate' => $orderCount > 0 ? round($completedOrders / $orderCount * 100, 2) : 0
        ];
    }
}
